package cn.wolfcode.trip.admin.filter;


import cn.wolfcode.trip.admin.controller.ImagesController;
import cn.wolfcode.trip.base.util.UploadUtil;
import lombok.Cleanup;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class ImagesFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String url = UploadUtil.PATH_All + req.getRequestURI();
        //创建url对象
        URL imgUrl = new URL(url);
        //获取URLConnection连接对象
        URLConnection urlConnection = imgUrl.openConnection();
        if(urlConnection.getContentLength()>0){
            byte[] buffer = new byte[8192];
            @Cleanup
            BufferedInputStream bufferedInputStream = new BufferedInputStream(urlConnection.getInputStream());
            @Cleanup
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            int len = -1;
            while(( len = bufferedInputStream.read(buffer)) != -1){
                bufferedOutputStream.write(buffer,0,len);
            }
            bufferedOutputStream.flush();
            return;
        }
        chain.doFilter(request,response);

    }

    @Override
    public void destroy() {

    }
}
